<template>
  <div>
    <div class="chat-container">
      <div class="chat-box" v-for="(msg, index) in messages" :key="index" :class="{'user': msg.user, 'bot': !msg.user}">
        <div class="message">{{ msg.text }}</div>
      </div>
      <div class="input-box">
        <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入你想了解的书籍..." />
        <button @click="sendMessage">Send</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      userInput: '',
      messages: []
    };
  },
  methods: {
    async sendMessage() {
      if (this.userInput.trim() === '') return;

      // 用户消息
      const userMessage = { text: this.userInput, user: true };
      this.messages.push(userMessage);
      const userInput = this.userInput;
      this.userInput = '';

      // 发送到文心一言API
      try {
        // 获取 access token
        const accessToken = await this.getAccessToken();

        // 构建请求
        const url = `api/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/yi_34b_chat?access_token=${accessToken}`;
        const payload = {
          "messages": [
            {
              "role": "user",
              "content": userInput
            }
          ],
          "temperature": 0.95,
          "top_p": 0.8,
          "penalty_score": 1,
          "disable_search": false,
          "enable_citation": false,
          "response_format": "text"
        };

        // 发送请求
        const response = await axios.post(url, payload, {
          headers: {
            'Content-Type': 'application/json'
          }
        });

        // 日志输出完整的响应数据
        console.log('API Response:', response);

        // 检查响应数据是否存在并提取消息
        if (response.data && response.data.result && response.data.result.length > 0) {
          const botMessage = { text: response.data.result.trim(), bot: true };
          this.messages.push(botMessage);
        } else {
          console.error('Invalid response structure', response.data);
          throw new Error('Invalid response structure');
        }
      } catch (error) {
        console.error('Error:', error.response ? error.response.data : error.message);
        const errorMessage = { text: 'Error communicating with the server. Please try again later.', bot: true };
        this.messages.push(errorMessage);
      }
    },
    async getAccessToken() {
      const url = "api/oauth/2.0/token";
      const params = {
        grant_type: "client_credentials",
        client_id: "sbIRuqcAugeTu5T5QbQyO9Ql",
        client_secret: "RJXMvpZ3sRms1gQoDmkqmTgpTaDDiY3d"
      };
      const response = await axios.post(url, null, { params });
      return response.data.access_token;
    }
  }
};
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  padding: 10px;
  margin-top: 20px;
}

.chat-box {
  display: flex;
  justify-content: flex-start;
  padding: 10px;
  margin: 5px 0;
}

.chat-box.user {
  justify-content: flex-end;
}

.message {
  max-width: 60%;
  padding: 10px;
  border-radius: 10px;
  background-color: #f1f1f1;
  font-size: 20px; 
}

.chat-box.user .message {
  background-color: #0084ff;
  color: white;
}

.input-box {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  font-size: 20px; 
}

input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button {
  padding: 10px 20px;
  margin-left: 10px;
  border: none;
  background-color: #0084ff;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  font-size: 20px; 
}
</style>
